class IndexDB {

    constructor() {
        this.init();
    }

    init () {
        const db = this.getIndexDB();
        if (!db) {
            throw new Error('浏览器不支持indexDB')
        }
        this.dBMap = new Map();
        this.db = db;
    }

    getIndexDB () {
        return window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
    }

    openIndexDBSuccess (dbId, __db) {
        console.log('数据库打开成功');
        this.dBMap.set(dbId, __db);
    }

    openIndexDBError () {
        console.log('数据库打开失败哦')
    }

    getDB (dbId) {
        if (!this.dBMap.has(dbId)) {
            this.createIndexDB(dbId);
        }
        return this.dBMap.get(dbId);
    }
    createIndexDB (dbId, version = 1) {
        if (this.dBMap.has(dbId)) {
            return this.dBMap.get(dbId);
        }

        const request = this.db?.open(dbId, version);
        request.onsuccess = () => {
            const _db = event.target.result;
            this.openIndexDBSuccess(dbId, _db);
        }
        request.onerror = this.openIndexDBError;



        return request;
    }

    addSuccess () {
        console.log('添加成功')
    }

    addError (e) {
        console.error('添加失败:\n', e)
    }

    addData (dbId, tableName, data) {
        console.log(this.dBMap)
        const _db = this.getDB(dbId);
        console.log(_db)
        const request = _db
            .transaction([tableName], 'readwrite')
            .objectStore(tableName)
            .add(data);

        request.onsuccess = this.addSuccess;
        request.onerror = this.addError;
    }

    deleteSuccess () {
        console.log('删除成功');
    }

    deleteError (e) {
        console.error('删除失败:\n', e);
    }
    deleteData (dbId, tableName, dataKey) {
        const _db = this.getDB(dbId);
        const request = _db
            .transaction([tableName], 'readwrite')
            .objectStore(tableName)
            .delete(dataKey);

        request.onsuccess = this.deleteSuccess;
        request.onerror = this.deleteError;
    }

    getSuccess () {
        console.log('获取成功');
    }

    getError (e) {
        console.error('获取失败:\n', e);
    }

    getData (dbId, tableName, dataKey) {
        const _db = this.getDB(dbId);
        const request = _db
            .transaction([tableName])
            .objectStore(tableName)
            .get(dataKey);

        request.onsuccess = this.getSuccess;
        request.onerror = this.getError;
    }
}


const indexDB = new IndexDB();
